package com.zhihuichongcheng.application.ui.cricle.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.smartlib.cmnObject.ui.NoScrollListView;
import com.smartlib.cmnObject.util.DateUtil;
import com.smartlib.cmnObject.util.DeviceUtil;
import com.smartlib.cmnObject.util.DialogUtil;
import com.smartlib.cmnObject.util.GsonUtil;
import com.smartlib.cmnObject.util.LogUtil;
import com.zhihuichongcheng.application.R;
import com.zhihuichongcheng.application.base.BaseActivity;
import com.zhihuichongcheng.application.bean.cricle.CommentBean;
import com.zhihuichongcheng.application.bean.cricle.CricleCategoryBean;
import com.zhihuichongcheng.application.bean.cricle.CricleImageInfo;
import com.zhihuichongcheng.application.bean.cricle.CricleLike;
import com.zhihuichongcheng.application.bean.cricle.HealthBean;
import com.zhihuichongcheng.application.bean.mine.UserBean;
import com.zhihuichongcheng.application.constant.NetworkAPI;
import com.zhihuichongcheng.application.glide.GlideCircleTransform;
import com.zhihuichongcheng.application.net.HttpCallback;
import com.zhihuichongcheng.application.ui.cricle.adapter.CommentAdapter;
import com.zhihuichongcheng.application.ui.cricle.adapter.CricleDeatilImageAdapter;
import com.zhihuichongcheng.application.ui.cricle.fragment.CircleHealthyFragment;
import com.zhihuichongcheng.application.util.SystemBarTintManager;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * Created by 3water on 2016/10/26.
 */

public class CricleDetailActivity extends BaseActivity implements View.OnClickListener {
    private ImageView mImAvatar, mImImage;
    private TextView mTvName, mTvTime, mTvTitle, mTvContent, mTvType, mTvCommentNum, mTvPariseNum, mTvSend;
    private NoScrollListView mRcvComment;
    private TextView mTvComment, mTvParise;
    private CommentAdapter mAdapter;
    private List<CommentBean> mListData = new ArrayList<>();
    private LinearLayout mLlBottom;
    private EditText mEtInput;
    private String mHomeId;
    private RelativeLayout mRlComment;
    private RecyclerView mRcvCricleDetailImg;
    private CricleDeatilImageAdapter mAdapterImg = null;
    private int width = 0;
    private TextView mTvPariseContent;
    private LinearLayout mLlParise, mLlComment;
    private List<CricleImageInfo> list;
    private TextView mTvNoComment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cricle_detail);
        SystemBarTintManager tintManager = new SystemBarTintManager(this);
        tintManager.setStatusBarTintEnabled(true);
        tintManager.setStatusBarTintResource(R.color.activity_color);//通知栏所需颜色
        initView();
        initData();
    }

    private void initView() {
        setTitle("详情");
        mTvNoComment = (TextView) findViewById(R.id.tv_noComment);
        mLlParise = (LinearLayout) findViewById(R.id.ll_parise);
        mLlComment = (LinearLayout) findViewById(R.id.ll_comment);
        mTvPariseContent = (TextView) findViewById(R.id.tv_pariseContent);
        mRcvCricleDetailImg = (RecyclerView) findViewById(R.id.rcv_cricleDetail_img);
        mRcvCricleDetailImg.setLayoutManager(new GridLayoutManager(mContext, 4) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        mTvSend = (TextView) findViewById(R.id.tv_send);
        mRlComment = (RelativeLayout) findViewById(R.id.rl_comment);
        mLlBottom = (LinearLayout) findViewById(R.id.ll_bottom);
        mEtInput = (EditText) findViewById(R.id.et_input);
        mTvComment = (TextView) findViewById(R.id.tv_comment);
        mTvParise = (TextView) findViewById(R.id.tv_parise);
        mImAvatar = (ImageView) findViewById(R.id.im_avatar);
        mTvName = (TextView) findViewById(R.id.tv_name);
        mTvTime = (TextView) findViewById(R.id.tv_time);
        mTvTitle = (TextView) findViewById(R.id.tv_title);
        mTvContent = (TextView) findViewById(R.id.tv_content);
        mTvType = (TextView) findViewById(R.id.tv_type);
        mTvCommentNum = (TextView) findViewById(R.id.tv_comment_num);
        mTvPariseNum = (TextView) findViewById(R.id.tv_parise_num);
        mImImage = (ImageView) findViewById(R.id.im_image);
        mRcvComment = (NoScrollListView) findViewById(R.id.rcv_comment);
        mAdapter = new CommentAdapter(mContext);
        mRcvComment.setAdapter(mAdapter);
        mRcvCricleDetailImg.setFocusable(false);

        mTvComment.setOnClickListener(this);
        mTvParise.setOnClickListener(this);
        mTvSend.setOnClickListener(this);
        mImImage.setOnClickListener(this);
    }

    private void initData() {
        width = DeviceUtil.getWidth(mContext);
        width = width - DeviceUtil.dip2px(mContext, 65);
        Intent intent = getIntent();
        if (intent != null && intent.hasExtra("homeId")) {
            mHomeId = intent.getStringExtra("homeId");
        }
        DialogUtil.showLoadDiadlog(mContext);
        loadData();
        loadComment();
    }

    private void loadData() {
        HashMap<String, String> params = new HashMap<>();
        params.put("token", mUser.getToken());
        params.put("jinbaoHomeId", mHomeId);
        mManager.post(NetworkAPI.CricleDetail, new HttpCallback() {
            @Override
            public void onSuccess(int code, String value, String msg) {
                DialogUtil.dismiss(mContext);
                HealthBean bean = GsonUtil.praseFromStringToBean(value, HealthBean.class);
                String pariseContent = "";
                List<CricleLike> listLikes = bean.getJinbaoLikes();
                for (int i = 0; i < listLikes.size(); i++) {
                    CricleLike cricleLike = listLikes.get(i);
                    UserBean userBean = null;
                    if (cricleLike != null) {
                        userBean = listLikes.get(i).getUser();
                    }
                    if (i == listLikes.size() - 1) {
                        if (userBean != null) {
                            pariseContent = pariseContent + userBean.getUserName();
                        }
                    } else {
                        if (userBean != null) {
                            pariseContent = pariseContent + listLikes.get(i).getUser().getUserName() + ",";
                        }
                    }
                }
                mTvPariseContent.setText(pariseContent);
                mTvTitle.setText(bean.getTitle());
                mTvContent.setText(bean.getContent());
                list = bean.getImgList();
                if (list != null && list.size() > 0) {
                    if (list.size() == 1) {
                        mImImage.setVisibility(View.VISIBLE);
                        mRcvCricleDetailImg.setVisibility(View.GONE);
                        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width / 3 * 2, width / 3 * 2);
                        params.setMargins(0, 0, 10, DeviceUtil.dip2px(mContext, 5));
                        mImImage.setLayoutParams(params);
                        Glide.with(mContext).load(list.get(0).getJinbaoHomeImgUrl()).into(mImImage);
                    } else if (list.size() <= 3) {
                        mImImage.setVisibility(View.GONE);
                        mRcvCricleDetailImg.setVisibility(View.VISIBLE);
                        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, width / 3);
                        mRcvCricleDetailImg.setLayoutParams(params);
                        CricleDeatilImageAdapter mAdapterImg = new CricleDeatilImageAdapter(mContext, list);
                        mRcvCricleDetailImg.setLayoutManager(new GridLayoutManager(mContext, 3));
                        mRcvCricleDetailImg.setAdapter(mAdapterImg);
                    } else if (list.size() <= 6) {
                        mImImage.setVisibility(View.GONE);
                        mRcvCricleDetailImg.setVisibility(View.VISIBLE);
                        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, width / 3 * 2);
                        mRcvCricleDetailImg.setLayoutParams(params);
                        CricleDeatilImageAdapter mAdapterImg = new CricleDeatilImageAdapter(mContext, list);
                        mRcvCricleDetailImg.setLayoutManager(new GridLayoutManager(mContext, 3));
                        mRcvCricleDetailImg.setAdapter(mAdapterImg);
                    } else {
                        mImImage.setVisibility(View.GONE);
                        mRcvCricleDetailImg.setVisibility(View.VISIBLE);
                        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, width);
                        mRcvCricleDetailImg.setLayoutParams(params);
                        CricleDeatilImageAdapter mAdapterImg = new CricleDeatilImageAdapter(mContext, list);
                        mRcvCricleDetailImg.setLayoutManager(new GridLayoutManager(mContext, 3));
                        mRcvCricleDetailImg.setAdapter(mAdapterImg);
                    }

                } else {
                    mRcvCricleDetailImg.setVisibility(View.GONE);
                    mImImage.setVisibility(View.GONE);
                }
                mRcvCricleDetailImg.setFocusable(false);
                ScrollView view = (ScrollView) findViewById(R.id.srrollVIew);
                view.setFocusable(true);
                view.requestFocus();
                Date date = DateUtil.parseStringToDate(bean.getCreateTime(), "yyyy年MM月dd日 HH:mm:ss");
                mTvTime.setText(DateUtil.format(date));
                UserBean user = bean.getUser();
                if (user != null) {
                    mTvName.setText(user.getUserName());
                    Glide.with(mContext).load(user.getLogoUrl()).transform(new GlideCircleTransform(mContext)).placeholder(R.drawable.ic_default_avatar).into(mImAvatar);
                } else {
                    mTvName.setText("");
                    Glide.with(mContext).load("").transform(new GlideCircleTransform(mContext)).placeholder(R.drawable.ic_default_avatar).into(mImAvatar);
                }
                CricleCategoryBean categoryBean = bean.getJinbaoHomeCategory();
                mTvType.setText(categoryBean.getCategoryName());
                mTvCommentNum.setText(bean.getCommentCount());
                mTvPariseNum.setText(bean.getLikeCount());
                List<CricleLike> cricleLikes = bean.getJinbaoLikes();
                for (int i = 0; i < cricleLikes.size(); i++) {
                    CricleLike like = cricleLikes.get(i);
                    if (like.getUserId().equals(mUser.getUserId())) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                            mTvParise.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.ic_cricle_already_parise, 0, 0, 0);
                        }
                        mTvParise.setTextColor(getResources().getColor(R.color.color_F06060));
                    }
                }
            }

            @Override
            public void onFailure(String value) {
                DialogUtil.dismiss(mContext);
            }
        }, params);
    }

    private void loadComment() {
        HashMap<String, String> params = new HashMap<>();
        params.put("token", mUser.getToken());
        params.put("jinbaoHomeId", mHomeId);
        mManager.post(NetworkAPI.CricleCommentList, new HttpCallback() {
            @Override
            public void onSuccess(int code, String value, String msg) {
                List<CommentBean> list = GsonUtil.paraeFromStringToList(value, CommentBean.class);
                mAdapter.setData(list);
                mAdapter.notifyDataSetChanged();
                if (list.size() == 0) {
                    mRcvComment.setVisibility(View.GONE);
                    mTvNoComment.setVisibility(View.VISIBLE);
                } else {
                    mRcvComment.setVisibility(View.VISIBLE);
                    mTvNoComment.setVisibility(View.GONE);
                }
            }

            @Override
            public void onFailure(String value) {

            }
        }, params);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_comment:
                mRlComment.setVisibility(View.VISIBLE);
                mLlParise.setVisibility(View.GONE);
                mLlComment.setVisibility(View.GONE);
                showKeyboard(mEtInput);
                mEtInput.requestFocus();
                break;
            case R.id.tv_parise:
                HashMap<String, String> param = new HashMap<>();
                param.put("token", mUser.getToken());
                param.put("jinbaoHomeId", mHomeId);
                mManager.post(NetworkAPI.CricleAddLike, new HttpCallback() {
                    @Override
                    public void onSuccess(int code, String value, String msg) {
                        if (code == 1) {
                            noticeRefreshList();
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                                mTvParise.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.ic_cricle_already_parise, 0, 0, 0);
                            }
                            mTvParise.setTextColor(getResources().getColor(R.color.color_F06060));
                            String parisecontent = mTvPariseContent.getText().toString();
                            if (TextUtils.isEmpty(parisecontent)) {
                                mTvPariseContent.setText(mUser.getUserName());
                            } else {
                                mTvPariseContent.setText(parisecontent + "," + mUser.getUserName());
                            }
                        }
                    }

                    @Override
                    public void onFailure(String value) {

                    }
                }, param);
                break;
            case R.id.tv_send:
                final String content = mEtInput.getText().toString();
                HashMap<String, String> params = new HashMap<>();
                params.put("jinbaoHomeId", mHomeId);
                params.put("token", mUser.getToken());
                params.put("content", content);
                mManager.post(NetworkAPI.CricleAddComment, new HttpCallback() {
                    @Override
                    public void onSuccess(int code, String value, String msg) {
                        noticeRefreshList();
                        CommentBean commentBean = new CommentBean();
                        commentBean.setContent(content);
                        commentBean.setUser(mUser);
                        //计算时间
                        String date = DateUtil.transferLongToDate("yyyy年MM月dd日 HH:mm:ss", System.currentTimeMillis());
                        commentBean.setCreateTime(date);
                        mAdapter.addItem(commentBean);
                        mAdapter.notifyDataSetChanged();
                        mEtInput.setText("");
                        mRcvComment.setVisibility(View.VISIBLE);
                        mTvNoComment.setVisibility(View.GONE);
                    }

                    @Override
                    public void onFailure(String value) {

                    }
                }, params);
                hideKeyboard(mEtInput);
                break;
            case R.id.im_image:
                Intent intent = new Intent(mContext, ShowImageActivity.class);
                intent.putParcelableArrayListExtra("list", (ArrayList) list);
                intent.putExtra("index", 0);
                mContext.startActivity(intent);
                ((Activity) mContext).overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
                break;
            default:
                break;
        }
    }

    private void noticeRefreshList() {
        LocalBroadcastManager.getInstance(getContext()).sendBroadcast(new Intent(CircleHealthyFragment.ACTION_UPDATE_HEALTHY_LIST));
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        LogUtil.logD(keyCode + "keycode");
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mRlComment.getVisibility() == View.VISIBLE) {
                mRlComment.setVisibility(View.GONE);
                mLlParise.setVisibility(View.VISIBLE);
                mLlComment.setVisibility(View.VISIBLE);
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        LogUtil.logD(keyCode + "keycode");
        return super.onKeyUp(keyCode, event);

    }


}
